// 题目描述

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var twoSumLessThanK = function (nums, k) {
  nums.sort((a, b) => a - b)

  let ans = -Infinity
  for (let i = 0; i < nums.length; i++) {
    const numsI = nums[i]
    if (numsI >= k) {
      break
    }
    const numsJMax = k - numsI
    let left = i + 1
    let right = nums.length - 1
    while (left <= right) {
      const mid = left + Math.floor((right - left) / 2)
      if (nums[mid] === numsJMax) {
        right = mid - 1
      } else if (nums[mid] < numsJMax) {
        left = mid + 1
      } else if (nums[mid] > numsJMax) {
        right = mid - 1
      }
    }

    if (right !== i && nums[right] < numsJMax) {
      const curSum = numsI + nums[right]
      ans = Math.max(ans, curSum)
    }
  }

  return (ans === -Infinity) ? -1 : ans
}

console.log(
  twoSumLessThanK(
    [358, 898, 450, 732, 672, 672, 256, 542, 320, 573, 423, 543, 591, 280, 399, 923, 920, 254, 135, 952, 115, 536, 143, 896, 411, 722, 815, 635, 353, 486, 127, 146, 974, 495, 229, 21, 733, 918, 314, 670, 671, 537, 533, 716, 140, 599, 758, 777, 185, 549],
    1800
  )
)
